<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script src="${APP_PATH}/static/js/jquery-1.12.4.min.js"></script>
<script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--员工修改模态框  -->
	<div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">员工修改</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" id="emp_update_form">
						<div class="form-group">
							<label for="inputEmail3" class="col-sm-2 control-label">EmpName</label>
							<div class="col-sm-10">
								<p class="form-control-static" id="emp_update_p_model"></p>
							</div>
						</div>
						<div class="form-group">
							<label for="inputPassword3" class="col-sm-2 control-label">Email</label>
							<div class="col-sm-10">
								<input type="text" name="email" class="form-control"
									id="email_update_input" placeholder="email@niit.com.cn">
									<span id="helpBlock2" class="help-block"></span>
							</div>
						</div>

						<div class="form-group">
							<label for="inputPassword3" class="col-sm-2 control-label">Gender</label>
							<div class="col-sm-10">
								<label class="radio-inline"> <input type="radio" name="gender" id="inlineRadio1" value="M" checked="checked">
									男
								</label> <label class="radio-inline"> <input type="radio" name="gender" id="inlineRadio2" value="F"> 女
								</label>
							</div>
						</div>

						<div class="form-group">
							<label for="inputPassword3" class="col-sm-2 control-label">Department</label>
							<div class="col-sm-4">
								<select class="form-control" name="dId" id="dept_update_select">
									
								</select>
							</div>
						</div>
					</form>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="emp_update_btn">保存</button>
				</div>
			</div>
		</div>
	</div>

	<!--员工添加模态框  -->

	<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">员工添加</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" id="emp_add_form">
						<div class="form-group">
							<label for="inputEmail3" class="col-sm-2 control-label">EmpName</label>
							<div class="col-sm-10">
								<input type="text" name="empName" class="form-control"
									id="empName_add_input" placeholder="empName">
									<span id="helpBlock2" class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="inputPassword3" class="col-sm-2 control-label">Email</label>
							<div class="col-sm-10">
								<input type="text" name="email" class="form-control"
									id="email_add_input" placeholder="email@niit.com.cn">
									<span id="helpBlock2" class="help-block"></span>
							</div>
						</div>

						<div class="form-group">
							<label for="inputPassword3" class="col-sm-2 control-label">Gender</label>
							<div class="col-sm-10">
								<label class="radio-inline"> <input type="radio" name="gender" id="inlineRadio1" value="M" checked="checked">
									男
								</label> <label class="radio-inline"> <input type="radio" name="gender" id="inlineRadio2" value="F"> 女
								</label>
							</div>
						</div>

						<div class="form-group">
							<label for="inputPassword3" class="col-sm-2 control-label">Department</label>
							<div class="col-sm-4">
								<select class="form-control" name="dId" id="dept_select">
									
								</select>
							</div>
						</div>
					</form>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
				</div>
			</div>
		</div>
	</div>

	<div class="container">
		<div class="row">
			<div class="col-md-12">
				<h1>SSM-CRUD</h1>
			</div>

		</div>
		<div class="row">
			<div class="col-md-4 col-md-offset-8">
				<button type="button" class="btn btn-primary" id="emp_add_btn">新增</button>
				<button type="button" class="btn btn-danger">删除</button>
			</div>
		</div>
		<div class="row">
			<div class="col-md-12">
				<table class="table table-hover">
					<thead>
						<tr>
							<th><input type="checkbox" id="check_all" ></th>
							<th>#</th>
							<th>empName</th>
							<th>gender</th>
							<th>email</th>
							<th>deptName</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody></tbody>
				</table>
			</div>

		</div>
		<div class="row">
			<!-- 分页信息栏 -->
			<div class="col-md-6" id="page_info_div"></div>
			<!-- 分页导航栏 -->
			<div class="col-md-6" id="page_nav_div"></div>
		</div>
	</div>
	<script type="text/javascript">
	
		//设置全局变量,保存记录数
		var totalRecord;
		
		$(function() {
			to_page(1);
		});

		function to_page(pn) {
			$.ajax({
				url : "${APP_PATH}/emps",
				type : "GET",
				data : "pn=" + pn,
				success : function(result) {
					//console.log(result);
					//1,解析并构建员工数据,填充进表格
					build_emps_table(result);
					//2,构建分页内容
					build_page_nav(result);
				}
			})
		}

		//构建员工表格
		function build_emps_table(result) {
			
			totalRecord = result.extend.pageInfo.total;
			//清空元素
			$("tbody").empty();

			var emps = result.extend.pageInfo.list;
			//构建表格
			$.each(emps,
					function(index, emp) {
						//alert(emp.empName);
						var checkTd= $("<td></td>").append($("<input>").attr("type","checkbox").addClass("check_item"));
						var empIdTd = $("<td></td>").append(emp.empId);
						var empNameTd = $("<td></td>").append(emp.empName);
						var genderTd = $("<td></td>").append(emp.gender=='M'?'男':'女');
						var emailTd = $("<td></td>").append(emp.email);
						var deptNameTd = $("<td></td>").append(
								emp.department.deptName);
						var editBtn = $("<button></button>").addClass(
								"btn btn-primary btn-sm edit-btn").append("编辑");
						//给编辑按钮增加自定义属性,存储对应id
						editBtn.attr("edit-id",emp.empId);
						
						var delBtn = $("<button></button>").addClass(
								"btn btn-danger btn-sm del-btn").append("删除");
						
						//给删除按钮增加自定义属性,存储对应id
						delBtn.attr("del-id",emp.empId);
						
						var btnTd = $("<td></td>").append(editBtn).append(
								delBtn);
						$("<tr></tr>").append(checkTd).append(empIdTd).append(empNameTd)
								.append(genderTd).append(emailTd).append(
										deptNameTd).append(btnTd).appendTo(
										$("tbody"));

					})
		}

		//构建分页内容
		function build_page_nav(result) {
			//清空元素
			$("#page_info_div").empty();
			$("#page_nav_div").empty();

			//构建分页信息栏
			$("#page_info_div").append(
					"当前第" + result.extend.pageInfo.pageNum + "页,共"
							+ result.extend.pageInfo.pages + "页,共"
							+ result.extend.pageInfo.total + "条记录");

			//构建分页导航栏

			var ulEle = $("<ul></ul>").addClass("pagination");

			var firstLi = $("<li></li>").append(
					$("<a></a>").attr("href", "#").append("首页"));

			if (result.extend.pageInfo.isFirstPage) {
				firstLi.addClass("disabled");
			} else {
				//增加点击事件
				firstLi.click(function() {
					to_page(1);
				});
			}

			var preLi = $("<li></li>").append(
					$("<a></a>").attr("href", "#").append("&laquo;"));

			if (!result.extend.pageInfo.hasPreviousPage) {
				preLi.addClass("disabled");
			} else {
				preLi.click(function() {
					to_page(result.extend.pageInfo.pageNum - 1);
				});
			}

			ulEle.append(firstLi).append(preLi);
			$.each(result.extend.pageInfo.navigatepageNums,
					function(index, num) {
						var numLi = $("<li></li>").append(
								$("<a></a>").attr("href", "#").append(num));

						numLi.click(function() {
							to_page(num);
						});

						if (result.extend.pageInfo.pageNum == num) {
							numLi.addClass("active");
						}

						ulEle.append(numLi);
					})
			var nextLi = $("<li></li>").append(
					$("<a></a>").attr("href", "#").append("&raquo;"));
			var lastLi = $("<li></li>").append(
					$("<a></a>").attr("href", "#").append("末页"));

			if (result.extend.pageInfo.isLastPage) {
				lastLi.addClass("disabled");
			} else {
				lastLi.click(function() {
					to_page(result.extend.pageInfo.pages);
				});
			}

			if (!result.extend.pageInfo.hasNextPage) {
				nextLi.addClass("disabled");
			} else {
				nextLi.click(function() {
					to_page(result.extend.pageInfo.pageNum + 1);
				});
			}

			ulEle.append(nextLi).append(lastLi);

			$("<nav></nav>").append(ulEle).appendTo($("#page_nav_div"));
		}

		//给新增按钮绑定点击事件
		$("#emp_add_btn").click(function() {
			//1,发送ajax请求,获取部门信息
			getDept("#dept_select");
			$('#empAddModal').modal();
		})
		
		//获取部门信息的方法
		function getDept(ele){
			$.ajax({
				url : "${APP_PATH}/depts",
				type : "GET",
				success : function(result) {
					//console.log(result);
					//<option value="1">开发部</option>
					//清空select子元素
					$(ele).empty();
					
					$.each(result.extend.list,function(index,dept){
						var optionEle = $("<option></option>").attr("value",dept.deptId).append(dept.deptName);
						$(ele).append(optionEle);
					});
				}
			})
		}
		
		//点击保存,发送ajax请求添加员工
		$("#emp_save_btn").click(function(){			
			//发送ajax请求验证用户名是否重复
			if($(this).attr("ajax-validate")=="fail"){
				return;
			}
			//前端jquery验证
			/* if(!validate_add_form()){
				return;
			} */
						
			//alert($("#emp_add_form").serialize());
			 $.ajax({
				url : "${APP_PATH}/emp",
				type : "POST",
				data : $("#emp_add_form").serialize(),
				success : function(result) {
					//console.log(result);
					
					if(result.code==100){
						//1,关闭模态框
						$('#empAddModal').modal("hide");
						//2,跳转至最后一页
						to_page(totalRecord);
					}else{
						console.log(result);
						//alert(result.extend.errors.empName);
						//alert(result.extend.errors.email);
						if(undefined != result.extend.errors.empName){
							show_validate_info("#empName_add_input","has-error","用户名应为5-16位字母数字组合!");
						}
						if(undefined != result.extend.errors.email){
							show_validate_info("#email_add_input","has-error","邮箱格式不正确!");
						}						
					}				
				}
			}) 
		});
		
		function validate_add_form(){
			
			
			//验证用户名
			var empName = $("#empName_add_input").val();			
			var regName= /^[a-zA-Z0-9_-]{5,16}$/;			
			if(!regName.test(empName)){
				//alert("用户名应为5-16位字母数字组合!");
				//$("#empName_add_input").parent().addClass("has-error");
				//$("#empName_add_input").next("span").text("用户名应为5-16位字母数字组合!");
				show_validate_info("#empName_add_input","has-error","用户名应为5-16位字母数字组合!");
				return false;
			}else{
				//$("#empName_add_input").parent().addClass("has-success");
				//$("#empName_add_input").next("span").text("");
				show_validate_info("#empName_add_input","has-success","");
			}			
			//验证邮箱
			var email = $("#email_add_input").val();			
			var regEmail= /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;			
			if(!regEmail.test(email)){
				//alert("邮箱格式不正确!");
				
				show_validate_info("#email_add_input","has-error","邮箱格式不正确!");
				return false;
			}else{
				show_validate_info("#email_add_input","has-success","");
			}			
			return true;
		}
		//显示验证信息
		function show_validate_info(ele,status,msg){
			
			$(ele).parent().removeClass("has-success has-error");
			
			$(ele).parent().addClass(status);
			$(ele).next("span").text(msg);
		}
		
		$("#empName_add_input").change(function(){
			var empName=$(this).val();
			
			$.ajax({
				url : "${APP_PATH}/checkEmpName",
				type : "POST",
				data : "empName="+empName,
				success : function(result) {
					//console.log(result);
					if(result.code==100){
						show_validate_info("#empName_add_input","has-success","用户名可用");
						$("#emp_save_btn").attr("ajax-validate","success");			
					}else{
						show_validate_info("#empName_add_input","has-error","用户名重复");
						$("#emp_save_btn").attr("ajax-validate","fail");	
					}
				}
			})
		})
		
		//给编辑按钮绑定点击事件
		$(document).on("click",".edit-btn",function(){
			//alert(1234);
			//获得部门信息
			getDept("#dept_update_select");
			//获得员工数据,回显
			getEmp($(this).attr("edit-id"));
			//将编辑按钮上的id值传递给修改模态框的保存按钮
			$("#emp_update_btn").attr("edit-id",$(this).attr("edit-id"));
			//打开修改模态框
			$('#empUpdateModal').modal();
		})
		
		//根据id获取员工数据并显示在编辑模态框
		function getEmp(id){
			$.ajax({
				url : "${APP_PATH}/emp/"+id,
				type : "GET",
				success : function(result) {
					//console.log(result);
					var emp=result.extend.emp;
					$("#emp_update_p_model").text(emp.empName);
					$("#email_update_input").val(emp.email);
					$("#empUpdateModal input[name=gender]").val([emp.gender]);
					$("#dept_update_select").val([emp.dId]);
				}
			})
		}
		
		//点击修改模态框保存按钮,修改员工数据
		$("#emp_update_btn").click(function(){
			//验证邮箱
			var email = $("#email_update_input").val();			
			var regEmail= /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;			
			if(!regEmail.test(email)){
				//alert("邮箱格式不正确!");
				
				show_validate_info("#email_update_input","has-error","邮箱格式不正确!");
				return false;
			}else{
				show_validate_info("#email_update_input","has-success","");
			}
			
			//发送ajax请求保存员工
			$.ajax({
				url : "${APP_PATH}/emp/"+$(this).attr("edit-id"),
				type : "PUT",
				data : $("#emp_update_form").serialize(),
				success : function(result) {
					//1,关闭模态框
					$('#empUpdateModal').modal("hide");
					//2,跳转至最后一页
					to_page(1);
				}
			}) 
		})
		
		//给编辑按钮绑定点击事件
		$(document).on("click",".del-btn",function(){
			var empId= $(this).attr("del-id");
			var empName= $(this).parents("tr").find("td:eq(2)").text();
			if(confirm("确认删除["+empName+"]吗?")){
				//发送ajax请求
				$.ajax({
					url : "${APP_PATH}/emp/"+empId,
					type : "DELETE",
					success : function(result) {
						alert(result.message);
						to_page(1);
					}
				}) 
			}
		})
		
		//完成全选/全部选
		$("#check_all").click(function(){
			$(".check_item").prop("checked",$(this).prop("checked"));
		})
		
		//check_item
		$(document).on("click",".check_item",function(){
			
			var b = $(".check_item:checked").length == $(".check_item").length;
			$("#check_all").prop("checked",b);
		})
	</script>
</body>
</html>